package com.example.shaomengjie.smvp.net.http;

import com.example.shaomengjie.smvp.net.api.ApiResponse;
import com.example.shaomengjie.smvp.net.exception.ApiException;
import com.example.shaomengjie.smvp.utils.Constant;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by shaomengjie on 2017/6/20.
 */

public class RxHelp {
    public static  <T> void toSubscribe(Observable<ApiResponse<T>> o, Observer<T> s) {
        o.subscribeOn(Schedulers.io())
                .map(new Function<ApiResponse<T>, T>() {
                    @Override
                    public T apply(@NonNull ApiResponse<T> response) throws Exception {
                        int code=response.getCode();
                        if (code!= Constant.SUCCESS_CODE) {
                            throw new ApiException(code, response.getMsg());
                        } else {
                            return response.getDatas();
                        }
                    }
                })
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s);
    }
}
